﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Data.Common;

namespace AspNetInfo.Diagnostics
{
    public class DatabaseConnectionTest : ITest
    {
        private ConnectionStringSettings _connectionStringSettings;


        public DatabaseConnectionTest(ConnectionStringSettings connString)
        {
            _connectionStringSettings = connString;
            Result = new TestResult { Status = TestStatus.New };
        }

        public TestResult Result
        {
            get;
            private set;
        }

        public string Name
        {
            get { return "DatabaseConnectionTest_" + _connectionStringSettings.Name; }
        }

        public string Description
        {
            get { return String.Format("Can connect to: {0}", _connectionStringSettings.ConnectionString); }
        }

        public TestResult Execute()
        {
            try
            {
                var provider = _connectionStringSettings.ProviderName;
                var factory = DbProviderFactories.GetFactory(provider);
                using (var conn = factory.CreateConnection())
                {
                    conn.ConnectionString = _connectionStringSettings.ConnectionString;
                    conn.Open();
                }
                Result.Status = TestStatus.Passed;
            }
            catch (Exception exc)
            {
                Result.Status = TestStatus.Failed;
                Result.Messages.Add(exc.Message);
                Result.Error = exc;
            }

            return Result;

        }


    }
}